//
//  YMChapterView.swift
//  YMSwiftUI
//
//  Created by anscen on 2022/3/31.
//

import SwiftUI


struct YMChapterView: View {

    var bookId :String
    @State var listData :[YMChapter] = []
    var body: some View {
        VStack {
            List(listData,id: \.self) { objc in
                NavigationLink.init {
                    YMDownContentView(chapter: objc)
                } label: {
                    YMChapterCell(title: objc.title, vip: objc.isVip)
                }
            }.onAppear {
                self.loadData()
            }.listStyle(.plain).padding(EdgeInsets.zero)
        }.navigationBarBackButtonHidden(true).navigationTitle("目录").navigationBarItems(leading: BaseNavigationBarBackButton())
    }
    func loadData(){
        YMChapter.getChapters(bookId) { model in
            if let model = model {
                DispatchQueue.global().async {
                    var datas :[YMChapter] = []
                    model.chapters?.forEach({ json in
                        if let chap = YMChapter.deserialize(from: json.rawString()){
                            datas.append(chap)
                        }
                    })
                    DispatchQueue.main.async {
                        self.listData = datas
                    }
                }
            }
        }
//        ApiMoya.request(target: .source(bookId)) { json in
//            guard let listData = [YMSource].deserialize(from: json.rawString()) else { return }
//            if let list = listData as? [YMSource],let source  = list.first{
//                ApiMoya.request(target: .chapters(source.sourceId)) { json in
//                    debugPrint(json)
//                    guard let listData = [YMChapter].deserialize(from: json["chapters"].rawString()) else { return }
//                    if let list = listData as? [YMChapter]{
//                        self.listData = list
//                    }
//                } failure: { error in
//
//                }
//            }
//        } failure: { error in
//
//        }
    }
}
struct YMChapterCell: View {
    var title :String
    var vip :Bool
    var body :some View{
        VStack {
            HStack(alignment: .center, spacing: 0) {
                Text(title).font(Font.system(size: 16, weight: .regular, design: .default)).foregroundColor(Color.appx333333()).lineLimit(1)
                Spacer()
                Text(vip ? "Vip" : "").padding(EdgeInsets.init(top: 0, leading: 0, bottom: 0, trailing: 15)).font(Font.system(size: 14)).foregroundColor(.red)
            }.padding(EdgeInsets(top: 15, leading: 0, bottom: 15, trailing: 0))
        }
    }
}

